<template>
  <div class="trading-terminal-view">

    <div>
      <el-row>
        <el-col :span="4">
          <!--                    <el-button class="border-btn" size="small" style="margin-bottom: 20px;" @click="changeClick">变更交易精细招商信息</el-button>-->
        </el-col>
        <el-col :span="20">
          <div style="display: flex; justify-content: flex-end">
            <el-form :inline="true" class="filter-form-inline" label-position="right" label-width="130px" size="small">
              <el-row :gutter="10">
                <el-col :span="16">
                  <el-form-item
                      label="产品信息"
                      style="width: 100%"
                  >
                    <el-select
                        v-model="formData.productId"
                        :loading="loading"
                        :remote-method="remoteMethod"
                        clearable
                        filterable
                        placeholder="请选择产品"
                        remote
                        reserve-keyword
                        @change="listSearch"
                    >
                      <el-option
                          v-for="item in products"
                          :key="item.id"
                          :label="item.productPopularName"
                          :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="">
                    <filter-popover
                        :form-list="formList"
                        right="20px"
                        @onConfirm="filterDataConfirm"
                        @onReset="filterReset"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-table :data="tableData" border header-cell-class-name="table-header" size="medium" @row-click="rowClick">
      <el-table-column align="left" fixed="left" header-align="center" label="终端名称" min-width="100" prop="terminalName"
                       show-overflow-tooltip type="tags"/>
      <el-table-column align="left" header-align="center" label="终端所在地区" min-width="100" show-overflow-tooltip
                       type="tags">
        <template #default="{row}">
          <span>{{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" header-align="center" label="产品名称" min-width="100"
                       prop="productInfoDetail.productPopularName" show-overflow-tooltip type="tags"/>
      <el-table-column align="center" label="批准文号" prop="productInfoDetail.approvalNumber" show-overflow-tooltip
                       type="tags"/>
      <el-table-column align="center" label="包装规格" prop="productInfoDetail.packSpecs" show-overflow-tooltip
                       type="tags"/>
      <el-table-column align="center" label="终端价(元)" type="tags">
        <template #default="{row}">
          <div>{{ row.terminalPrice }}</div>
          <div
              v-if="row.processDefinitionKey==='productPriceChange'&&row.flowStatus==='DOING'"
              class="flow-status-color"
          >
            [终端价变更审核中]
          </div>
          <div
              v-if="row.processDefinitionKey==='relationStandardChangeTerminalPrice'&&row.flowStatus==='DOING'"
              class="flow-status-color"
          >
            [更换终端价审核中]
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="交易价(元)" type="tags">
        <template #default="{row}">

          <div>{{ row.tradePrice }}</div>
          <div
              v-if="(row.processDefinitionKey == 'agentProductChangePrice' || row.processDefinitionKey == 'agentPersonProductChangePrice') && row.flowStatus=='DOING'"
              class="flow-status-color"
          >交易价变更审核中
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="配送商" min-width="150" type="tags">
        <template #default="{row}">
          <distributors-view v-if="row.distributeContractDetails && row.distributeContractDetails.length"
                             :datas="row.distributeContractDetails" :unit="row.productInfoDetail?.sellUnit"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上月营销额" prop="lastMonthSale" type="tags">
        <template #default="{row}">

          <div class="tab-line">
            <div v-if="row.lastMonthSale">{{ row.lastMonthSale }}</div>
            <div v-else>0</div>
            <div v-if="row.lastMonthSale && row.lastlastMonthSale && (row.lastlastMonthSale != row.lastMonthSale)"
                 :class="dealSellNum(row.lastlastMonthSale,row.lastMonthSale).class">
              {{ dealSellNum(row.lastlastMonthSale, row.lastMonthSale).str }}
            </div>
          </div>

        </template>
      </el-table-column>
      <el-table-column align="center" label="本月营销额" prop="thisMonthSale" type="tags">
        <template #default="{row}">

          <div class="tab-line">
            <div v-if="row.thisMonthSale">{{ row.thisMonthSale }}</div>
            <div v-else>0</div>
            <div v-if="row.lastMonthSale && row.thisMonthSale && (row.thisMonthSale != row.lastMonthSale)"
                 :class="dealSellNum(row.lastMonthSale,row.thisMonthSale).class">
              {{ dealSellNum(row.lastMonthSale, row.thisMonthSale).str }}
            </div>
          </div>

        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" type="tags" width="160">
        <template #default="{row}">
          <div> {{ getLabel('fine_terminal', row.devStatus) }}</div>
          <div
              v-if="row.processDefinitionKey == 'relationStandardChangeAgent' && row.flowStatus=='DOING'"
              class="flow-status-color"
          >{{ getLabel('approval_result', row.flowStatus) }}
          </div>
        </template>
      </el-table-column>
      <!--            <el-table-column label="操作" fixed="right" align="center">-->
      <!--                <template #default="{row}">-->
      <!--                    <el-button type="text" v-if="row.standardStatus == 1" @click.stop="endClick(row)">终止交易</el-button>-->
      <!--                </template>-->
      <!--            </el-table-column>-->
    </el-table>

    <change-trading-dialog ref="changeTrading" :agent="datas" @success="success"/>

    <detail-drawer ref="detailDrawer" :size-width="1000" custom-title>
      <template #title>
        <span class="min-txt">交易终端详情-</span>
        <span class="detailTitle">{{ selectData.terminalName }}</span>
        <span class="flow-status-color min-txt">[  {{ getLabel('fine_terminal', selectData.devStatus) }} ]</span>
      </template>
      <template #contents>

        <details-view :datas="selectData"/>

      </template>
    </detail-drawer>

  </div>
</template>

<script>
import detailsView from './modules/detailsView.vue'
import changeTradingDialog from './modules/changeTradingDialog.vue'
import {useRoute, useRouter} from 'vue-router'
import {defineComponent, getCurrentInstance, inject, onBeforeMount, reactive, toRefs} from 'vue'

export default defineComponent({
  name: 'Index',
  components: {changeTradingDialog, detailsView},
  props: {
    datas: {
      type: Object,
      default: {}
    }
  },
  setup(props) {
    const currentInstance = getCurrentInstance()
    const router = useRouter()
    const route = useRoute()
    const api = inject('api')

    var data = reactive({
      tableData: [],
      formData: {
        page: 1,
        pageSize: 20,
        agentId: '',
        productId: '',
        standardStatus: '',
        provinceCode: '',
        cityCode: '',
        areaCode: ''
      },
      total: 0,
      changeTrading: null,
      selectData: null,
      detailDrawer: null,
      loading: false,
      products: [],
      formList: [
        {
          key: 'standardStatus',
          label: '状态',
          form_type: 'select',
          value: '',
          is_search: false,
          options: [
            {
              value: '-1',
              label: '已终止交易'
            },
            {
              value: '1',
              label: '正常交易'
            }
          ],
        },
        {
          key: 'area',
          label: '所在地区',
          form_type: 'cascader',
          value: [],
          is_search: false,
          multiple: false,
          options: [],
        },
      ]
    })

    const remoteMethod = (query) => {
      data.products = []
      data.loading = true

      const a = {
        id: props.datas.id,
        type: '2',
        productPopularName: ''
      }
      if (query) {
        a.productPopularName = query
      }

      api.signedAgent.RELATIONSTANDARD_PRODUCT_LIST(a).then(res => {
        data.loading = false
        if (!res.code && res.data) {
          res.data.agentProduct.forEach(item => {
            item.name = item.productPopularName + item.packSpecs + item.approvalNumber
          })
          data.products = res.data.agentProduct
        }
      })
    }

    const filterDataConfirm = (formdata) => {
      data.formData.standardStatus = formdata.standardStatus
      if (formdata.area && formdata.area.length) {
        data.formData.provinceCode = formdata.area[0]
        data.formData.cityCode = formdata.area[1]
        data.formData.areaCode = formdata.area[2]
      } else {
        data.formData.provinceCode = ''
        data.formData.cityCode = ''
        data.formData.areaCode = ''
      }
      getListData()
    }

    const filterReset = () => {
      data.formData = {
        page: 1,
        pageSize: 20,
        agentId: '',
        productId: '',
        standardStatus: '',
        provinceCode: '',
        cityCode: '',
        areaCode: ''
      }
      getListData()
    }

    const changeClick = () => {
      data.changeTrading.openDialog()
    }

    const rowClick = (row) => {
      data.selectData = row
      data.detailDrawer.open()
    }

    const getStatus = (row) => {
      switch (row.standardStatus) {
        case '-1':
          return '已终止交易'
        case '1':
          return '正常交易'
      }
    }

    const listSearch = () => {
      data.formData.page = 1
      getListData()
    }

    const success = () => {
      getListData()
    }

    const getListData = (id) => {
      const a = JSON.parse(JSON.stringify(data.formData))
      a.agentId = Number(route.query.id)
      a.productId = Number(a.productId)

      api.signedAgent.TRADING_TERMINAL_LIST(a).then(res => {
        if (!res.code && res.data) {
          data.tableData = res.data.list
          data.total = res.data.total
        }
      })
    }

    const endClick = (row) => {
      currentInstance.proxy
          .alertBox({
            message: '是否确认终止该交易？',
            title: '终止交易',
          })
          .then(() => {
            api.signedAgent.TRADING_TERMINAL_END(row.id).then(res => {
              if (!res.code) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '操作成功',
                })

                getListData(route.query.id)
              }
            })
          })
          .catch((err) => {
            console.log(err)
          })
    }

    const dealSellNum = (last, now) => {
      if (last == now || !last || !now) {
        return {}
      }
      let classStr = ''
      let unit = ''
      const num = (now - last) / last * 100

      if (num < 0) {
        classStr = 'desc-num'
        unit = '↓'
      } else {
        classStr = 'asc-num'
        unit = '↑'
      }
      const str = num.toFixed(2) + '%' + unit
      return {class: classStr, str: str}
    }

    onBeforeMount(() => {
      if (route.query.id) {
        getListData(route.query.id)
      }
    })

    return {
      ...toRefs(data),

      rowClick,
      changeClick,
      getStatus,
      endClick,
      remoteMethod,
      listSearch,
      filterDataConfirm,
      filterReset,
      success,
      dealSellNum,
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@/style/basics.scss';

.trading-terminal-view {
  .detailTitle {
    font-size: $font-size-title;
    color: $font-color-main;
    padding: 0 $block-x;
  }

  .min-txt {
    font-size: $font-size-info;
  }

  .desc-num {
    color: chartreuse;
  }

  .asc-num {
    color: $delete-color;
  }
}

</style>
